package com.laomuji.android.mvvm.utils.language

import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Build
import android.os.LocaleList
import android.webkit.WebView
import androidx.core.os.ConfigurationCompat
import com.laomuji.android.mvvm.utils.PackageUtil
import java.util.Locale


/**
 * 国际化的语言设置
 * @author laomuji666
 * @since 2024/2/20
 */
object LanguageUtil {

    /**
     * WebView第一次打开会重置app的语言,可以在app启动页加载时,创建然后销毁,WebView(context).destroy()
     */
    fun initLanguage(context: Context){
        WebView(context).destroy()
    }

    /**
     * 设置app的语言
     * 设置完成需要重新加载app
     */
    fun setAppLanguage(languageCode: LanguageCode){
        //保存最新的国家码
        LanguageCode.setLastLanguageCode(languageCode)
        //获取国家码对应的locale
        val locale= Locale(languageCode.getAndroidLanguageCode())
        //把能设置的语言都修改
        updateLanguage(PackageUtil.getApplicationContext(),locale)
        for (baseActivity in PackageUtil.getAllActivity()) {
            updateLanguage(baseActivity, locale)
        }
    }

    private fun updateLanguage(context: Context, locale: Locale){
        //设置app的语言
        val resources = context.resources
        val configuration: Configuration = resources.configuration
        configuration.setLocale(locale)
        if (Build.VERSION.SDK_INT >= 24) {
            configuration.setLocales(LocaleList(locale))
        }
        //updateConfiguration的替换方案
        context.createConfigurationContext(configuration)
        //虽然标记了废弃,但是仍然需要使用,防止resource切换不生效.
        resources.updateConfiguration(configuration,resources.displayMetrics)
    }


    /**
     * 获取系统首选语言
     */
    fun getSysPreferredLocale(): Locale {
        try {
            val locale: Locale? =
                ConfigurationCompat.getLocales(Resources.getSystem().configuration).get(0)
            if (locale != null) {
                return locale
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return Locale.ENGLISH
    }
}